/*
 *  Copyright (c) 2018, Infineon Technologies AG
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification,are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holders nor the names of its contributors
 *  may be used to endorse or promote products derived from this software without
 *  specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *  LIABLE  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  To improve the quality of the software, users are encouraged to share
 *  modifications, enhancements or bug fixes with Infineon Technologies AG
 *  dave@infineon.com).
 */
/**
 * \file	Main.c
 * \author 	Manuel Escudero Rodriguez
 * \date	09.05.2018
 * \brief   Main function
 *
 * Phase Shift Full Bridge. Peak Current Mode Control.
 */
/*
 *  Copyright (c) 2018, Infineon Technologies AG
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification,are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holders nor the names of its contributors
 *  may be used to endorse or promote products derived from this software without
 *  specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *  LIABLE  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  To improve the quality of the software, users are encouraged to share
 *  modifications, enhancements or bug fixes with Infineon Technologies AG
 *  dave@infineon.com).
 */
/**
 * \copyright
 *      Copyright (c) 2018, Infineon Technologies AG
 *      <br>All rights reserved.
 *      <br>Redistribution and use in source and binary forms, with or without
 *      modification,are permitted provided that the following conditions are met:
 *      - Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *      - Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *      - Neither the name of the copyright holders nor the names of its contributors
 *      may be used to endorse or promote products derived from this software without
 *      specific prior written permission.
 *      .
 *      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *      AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *      IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *      ARE  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *      LIABLE  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *      CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *      SUBSTITUTE GOODS OR  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *      INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *      CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *      ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *      POSSIBILITY OF SUCH DAMAGE.
 *      <br>To improve the quality of the software, users are encouraged to share
 *      modifications, enhancements or bug fixes with Infineon Technologies AG
 *      dave@infineon.com).
 */
/**
 * \mainpage Phase Shift Full Bridge XMC4200
 *      <b>Project frame:</b>
 *      - 3300W Phase shift full bridge.
 *      - Switching frequency 100KHz.
 *      - Peak current mode control.
 *      - Cycle by cycle input current limit.
 *      - HICCUP output overcurrent protection.
 *      - Soft start.
 *      - Brown in, brown out.
 *      - Output over voltage protection.
 *      - Output under voltage protection.
 *      - Synchronous rectifiers control, three modes of operation.
 *      - Serial communication UART.
 *      - Remote parametrization and storage of settings on FLASH on chip.
 *      - Burst mode.
 *      - Bridge adaptive dead times.
 *      - Synchronous adaptive dead times.
 * \dot
 * digraph example
 * {
 *      node [ shape=ellipse, fontname=Helvetica, fontsize=10 ];
 *      START_UP [ label="START_UP" ];
 *      FAIL [ shape="doublecircle", label="FAIL", color="red" ];
 *      OFF [ shape="doublecircle", label="OFF", color="blue" ];
 *      ON [ label="ON" ];
 *      BURST [ label="BURST" ];
 *      OFF -> START_UP [ arrowhead="open", shape="curve", label="brown in" ];
 *      START_UP -> ON [ arrowhead="open", shape="curve", label="regulation" ];
 *      START_UP -> FAIL [ arrowhead="open", shape="curve", label="time out" ];
 *      START_UP -> FAIL [ arrowhead="open", shape="curve", label="over current" ];
 *      FAIL -> OFF [ arrowhead="open", shape="curve", label="" ];
 *      ON -> BURST [ arrowhead="open", shape="curve", label="no load" ];
 *      ON -> FAIL [ arrowhead="open", shape="curve", label="protections" ];
 *      ON -> OFF [ arrowhead="open", shape="curve", label="brown out" ];
 *      ON -> START_UP [ arrowhead="open", shape="curve", label="hiccup" ];
 *      BURST -> ON [ arrowhead="open", shape="curve", label="load increase" ];
 * }
 * \enddot
 */
#include <XMC4200.h>
#include <DAVE.h>
#include "controller.h"
#include "controller_boost.h"
#include "controller_buck.h"
#include "config_adc.h"
#include "communication.h"

/* Declare these as volatile to avoid compiler optimizations. */
volatile uint16_t dely_i, dely_j;
static uint16_t zero_adc_io_cnt;

uint32_t adc_io_zero_test = 0;
uint32_t adc_io_zero_test_before = 0;
/*---------------------------------------------------------------------------*/
/**
 * \brief	Sets zero level of IO current measurement
 * \return	None
 * 
 * Note: zero level of current should be falling around mid point of scale.
 * If controller is started right at same time than output capacitance is 
 * being charged it will be measuring current, so function should retry to set
 * a zero.
 */
void adc_io_set_zero()
{
	while (((current_ctr.adc_io_zero > ADC_IO_MID_POINT_HIGH) || (current_ctr.adc_io_zero < ADC_IO_MID_POINT_LOW)) && (zero_adc_io_cnt < ZERO_ADC_IO_MAX_TRIAL))
	{
		dely_j = 10000;
		while(--dely_j);
		{
			dely_i = 50000;
			while(--dely_i)
			{
				/* Average of output current reading when converter is OFF. */
				current_ctr.adc_io_zero = ((current_ctr.adc_io_zero * ADC_IO_ZERO_FACTOR) + ADC_IO_RESULT) >> ADC_IO_ZERO_RATIO;
			}
		}
		/* Limit amount of trials before triggering an error of zeroing ADC io. */
		zero_adc_io_cnt ++;
	}
}
/*---------------------------------------------------------------------------*/
/**
 * \brief	Main function
 * \return 	None
 */
int main(void)
{
	DAVE_Init();
	adc_init();
	die_temp_sens_init();
    load_ROM_parameters();
    check_RAM_parameters();
	voltage_ctr_init();
	current_ctr_init();
	pwm_init();
	pwm_start();
	/* 
	 * Intentional delay to allow ADC to initialize correctly. 
	 * Note: CPU starts before VDD reaches 3.3V. ADC would not measure at the
	 * right scaling before VDD is at the final 3.3V. 
	 * Workaround: Ensure 3.3V is reached, do a startup calibration after to 
	 * remove this delay.
	 */
	dely_j = 10000;
	while(--dely_j);
	{
	    dely_i = 50000;
	    while(--dely_i);
	}
	/* 
	 * Adjustment of bidirectional output current measurement zero point. 
	 */
	adc_io_zero_test_before = current_ctr.adc_io_zero;
	adc_io_set_zero();

	if(ADC_VIN_RESULT < 2400)//91V  boost模式下低压侧输入48V，空载模式下低压侧电流与demo板差了0.2A（demo板DCDC-DCAC连起来使用时为0.8A，而我们自己的板子DCDC-DCAC连起来使用时为0.6A，补上了这个后也达到了0.8A）
		current_ctr.adc_io_zero += 8;//此补偿条件与补偿数都是测出来的，不是计算出来的

	adc_io_zero_test = current_ctr.adc_io_zero;
	/* Reset controller to known status and buck mode as default. */
    buck_start_up_init();
    /* Check of output current initialization adc. */
    if(zero_adc_io_cnt < ZERO_ADC_IO_MAX_TRIAL)
    {
    	/* OFF by default. Will start up in low priority routines. */
    	converter_ctr.status |= OFF;
    }
    else
    {
    	/* Latches converter into an error. */
    	converter_ctr.status |= OFF;
    	converter_ctr.status |= START_FAIL;
    	converter_ctr.status |= TRAPPING;
    }
   converter_ctr.status &= ~START_EN;//这里关闭掉DCDC的上电后就立刻使能的转换功能，而是通过上位机指令来启动它（包括buck模式和boost模式）
	// Debugging. Later on this will be set by UART or by external switch.
	//boost_mode_init();
	// Debugging

    /* Enable control loop execution. */
    COMPENSATOR_ON();
    /* Low priority task would be executed during idle time of control loop. */
	low_priority_task();
}
